import math

import pygame
import Sprite_Group
import random
from Config import FONT,MAXLV

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (252,203,22)
H_YELLOW= (251,218,65)
TRANSPAREN = (0,0,0,0)

def move(character, speed, direction):
    # 检查墙壁碰撞
    def check_wall_collision(s, d):
        new_x = character.rect.x
        new_y = character.rect.y

        # 根据方向计算新位置
        if d == 'L':
            new_x -= s
        elif d == 'R':
            new_x += s
        elif d == 'U':
            new_y -= s
        elif d == 'D':
            new_y += s

        # 创建一个临时的矩形来表示新位置
        new_rect = character.rect.copy()
        new_rect.x = new_x
        new_rect.y = new_y

        # 检查新位置是否与任何墙发生碰撞
        for wall in Sprite_Group.Wall_group:
            if new_rect.colliderect(wall.rect):
                # 如果有碰撞，调整角色的位置
                if d == 'L':  # 向左移动时碰撞
                    character.rect.left = wall.rect.right
                elif d == 'R':  # 向右移动时碰撞
                    character.rect.right = wall.rect.left
                elif d == 'U':  # 向上移动时碰撞
                    character.rect.top = wall.rect.bottom
                elif d == 'D':  # 向下移动时碰撞
                    character.rect.bottom = wall.rect.top
                return True  # 发生了碰撞并已处理
        return False  # 没有发生碰撞

    # 检查与其它角色碰撞
    def check_character_collision(s, d):
        new_x = character.rect.x
        new_y = character.rect.y
        if d == 'L':
            new_x -= s
        elif d == 'R':
            new_x += s
        elif d == 'U':
            new_y -= s
        elif d == 'D':
            new_y += s

        # 创建一个临时的矩形来表示新位置
        new_rect = character.rect.copy()
        new_rect.x = new_x
        new_rect.y = new_y

        # 检查与其它角色碰撞
        for enemy in Sprite_Group.Enemy_group:
            if enemy != character and new_rect.colliderect(enemy.rect):
                return True
        for player in Sprite_Group.Player_group:
            if player != character and new_rect.colliderect(player.rect):
                return True
        return False

    # 如果方向改变，则重置当前帧
    if direction!= character.direction:character.current_frame = 0

    character.direction = direction
    character.image = character.images[character.direction][character.current_frame]

    # 执行移动前检查
    if not check_wall_collision(speed,direction) and  not check_character_collision(speed,direction):
        # 根据方向更新位置
        if direction== 'L':
            character.rect.x -= speed
        elif direction == 'R':
            character.rect.x += speed
        elif direction== 'U':
            character.rect.y -= speed
        elif direction== 'D':
            character.rect.y += speed

def auto_move(character, speed, direction):
    def check_wall_collision(s, d):
        new_x = character.rect.x
        new_y = character.rect.y

        # 根据方向计算新位置
        if d == 'L':
            new_x -= s
        elif d == 'R':
            new_x += s
        elif d == 'U':
            new_y -= s
        elif d == 'D':
            new_y += s

        # 创建一个临时的矩形来表示新位置
        new_rect = character.rect.copy()
        new_rect.x = new_x
        new_rect.y = new_y

        # 检查新位置是否与任何墙发生碰撞
        for wall in Sprite_Group.Wall_group:
            if new_rect.colliderect(wall.rect):
                # 如果有碰撞，调整角色的位置
                if d == 'L':  # 向左移动时碰撞
                    character.rect.left = wall.rect.right
                elif d == 'R':  # 向右移动时碰撞
                    character.rect.right = wall.rect.left
                elif d == 'U':  # 向上移动时碰撞
                    character.rect.top = wall.rect.bottom
                elif d == 'D':  # 向下移动时碰撞
                    character.rect.bottom = wall.rect.top
                return True  # 发生了碰撞并已处理
        return False  # 没有发生碰撞

    def check_character_collision(s, d):
        new_x = character.rect.x
        new_y = character.rect.y
        if d == 'L':
            new_x -= s
        elif d == 'R':
            new_x += s
        elif d == 'U':
            new_y -= s
        elif d == 'D':
            new_y += s

        # 创建一个临时的矩形来表示新位置
        new_rect = character.rect.copy()
        new_rect.x = new_x
        new_rect.y = new_y

        # 检查与其它角色碰撞
        for enemy in Sprite_Group.Enemy_group:
            if enemy != character and new_rect.colliderect(enemy.rect):
                return True
        for player in Sprite_Group.Player_group:
            if player != character and new_rect.colliderect(player.rect):
                return True
        return False

    def randomd():
        return random.choice(['U', 'D', 'L', 'R'])

    if direction != character.direction: character.current_frame = 0

    character.direction = direction
    character.image = character.images[character.direction][character.current_frame]

    # 执行移动前检查
    if  check_wall_collision(speed, direction) or check_character_collision(speed, direction):

        dd = randomd()
        while dd==direction : dd=randomd()
        move(character,speed,dd)
    # 如果有碰撞则保持原位
    else:
        # 根据方向更新位置
        if direction == 'L':
            character.rect.x -= speed
        elif direction == 'R':
            character.rect.x += speed
        elif direction == 'U':
            character.rect.y -= speed
        elif direction == 'D':
            character.rect.y += speed

def draw_bordered_rectangle(screen, rect, border_color, fill_color):
        # 绘制有边框的矩形
    pygame.draw.rect(screen, fill_color, rect)
    pygame.draw.rect(screen, border_color, rect, 1)

def create_health_bar(character, width, height, dic='l'):
    image = pygame.Surface((width, height), pygame.SRCALPHA)  # 创建透明图像
    image.fill((0, 0, 0, 0))  # 用透明色填充

    # 计算当前单位的生命值宽度
    now_hp_len = width * character.hp / character.max_hp

    # 绘制背景矩形（代表最大生命值）
    bg_rect = pygame.Rect(0, 0, width, height)  # 背景矩形
    draw_bordered_rectangle(image, bg_rect, BLACK, RED)

    if dic == 'l':
        hp_rect = pygame.Rect(0, 0, now_hp_len, height)
    else:
        hp_rect = pygame.Rect(width - now_hp_len, 0, now_hp_len, height)
    draw_bordered_rectangle(image, hp_rect, BLACK, GREEN)

    return image

def create_exp_bar(character, width, height, dic='l'):

    image = pygame.Surface((width, height), pygame.SRCALPHA)  # 创建透明图像
    image.fill((0, 0, 0, 0))  # 用透明色填充

    # 计算当前单位的生命值宽度
    now_exp_len = width * character.exp / character.max_exp

    # 绘制背景矩形（代表最大生命值）
    bg_rect = pygame.Rect(0, 0, width, height)  # 背景矩形
    draw_bordered_rectangle(image, bg_rect, BLACK,TRANSPAREN)

    if character.level == MAXLV :
        exp_rect = pygame.Rect(0, 0, width, height)
    elif dic == 'l':
        exp_rect = pygame.Rect(0, 0, now_exp_len, height)
    else:
        exp_rect = pygame.Rect(width - now_exp_len, 0, now_exp_len, height)
    draw_bordered_rectangle(image, exp_rect, BLACK,H_YELLOW)

    return image

def render_text(text, font_size,font_color):
    # 初始化 Pygame
    pygame.init()

    # 初始化字体模块
    pygame.font.init()

    # 加载字体，None 表示使用默认字体
    font = pygame.font.Font(FONT, font_size)

    # 渲染文本，第三个参数是颜色，这里用白色 (255, 255, 255) 作为例子
    text_surface = font.render(text, True, font_color)

    return text_surface

def draw_filled_equilateral_triangle(surface, rect, color, direction='left'):
    """
    绘制一个填充颜色的等边三角形。

    :param surface: 画布，类型为 pygame.Surface
    :param rect: 确定三角形位置和大小的矩形，类型为 pygame.Rect
    :param color: 填充颜色，格式为 (R, G, B)
    :param direction: 三角形的方向，'left' 或 'right'
    """
    # 获取矩形的宽度，它将是等边三角形底边的长度
    base = rect.width

    # 计算高度
    height = (math.sqrt(3) / 2) * base

    if direction == 'left':
        # 向左的等边三角形
        points = [
            (rect.left - (height - rect.height / 2), rect.centery),  # 顶点在左边线外
            (rect.right, rect.top),                                  # 右上角
            (rect.right, rect.bottom)                                # 右下角
        ]
    else:
        # 向右的等边三角形
        points = [
            (rect.right + (height - rect.height / 2), rect.centery), # 顶点在右边线外
            (rect.left, rect.top),                                   # 左上角
            (rect.left, rect.bottom)                                 # 左下角
        ]

    # 使用 polygon 函数绘制并填充三角形
    pygame.draw.polygon(surface, color, points)
